"""
Case Type   : gs_preupgradechk工具
Case Name   : 数据库enable_memory_limit=off时gs_preupgradechk工具A6项检测
Create At   : 2025/11/17
Owner       : chen
Description :
    1.设置enable_memory_limit为off
    2.检测A6项
Expect      :
    1.成功
    2.成功
History     :
"""

import unittest
import os
import re
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')

class Tools_Gs_Preupgradechk_TestCase0015(unittest.TestCase):
    def setUp(self):
        LOG.info(f'----{os.path.basename(__file__)} start----')
        self.pri_node = Node('PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.mem_param = 'enable_memory_limit'
        LOG.info("---SetUp：检查数据库状态是否正常---")
        status = primary_sh.get_db_cluster_status()
        LOG.info(status)
        self.assertTrue("Degraded" in status or "Normal" in status)

    def test_gs_preupgradechk_tools(self):
        text = '----step1: 设置enable_memory_limit为off; expect: 成功----'
        LOG.info(text)
        self.def_mem = self.com.show_param(self.mem_param)
        set_param = primary_sh.execute_gsguc('set',
                            self.constant.GSGUC_SUCCESS_MSG,
                            f"{self.mem_param}='off'")
        LOG.info(set_param)
        self.assertTrue(set_param)
        res = primary_sh.restart_db_cluster()
        self.assertTrue(res)

        text = '----step2: 检测A6项; expect: 成功----'
        LOG.info(text)
        cmd = f"gs_preupgradechk -i A6"
        LOG.info(cmd)
        result = self.pri_node.sh(f"source {macro.DB_ENV_PATH};"
                                    f"{cmd}").result()
        LOG.info(result)
        self.assertIn('Successfully checked database usage status', result)
        self.assertIn('Normal', result)
        self.assertNotIn('max_process_memory', result)
        self.assertNotIn('process_used_memory', result)

    def tearDown(self):
        LOG.info('--------清理环境--------')
        set_param = primary_sh.execute_gsguc('set',
                            self.constant.GSGUC_SUCCESS_MSG,
                            f"{self.mem_param}='{self.def_mem}'")
        LOG.info(set_param)
        self.assertTrue(set_param)
        res = primary_sh.restart_db_cluster()
        self.assertTrue(res)
        status = primary_sh.get_db_cluster_status("detail")
        LOG.info(status)
        self.assertTrue("Degraded" in status or "Normal" in status)
        LOG.info(f"------{os.path.basename(__file__)} end------")
